import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Article } from './entities/article.entity';
import { VectorService } from './vector.service';
import * as fs from 'fs';
import * as path from 'path';
import * as mammoth from 'mammoth';
import * as pdfParse from 'pdf-parse';

@Injectable()
export class ArticleService {
  constructor(
    @InjectRepository(Article)
    private readonly articleRepository: Repository<Article>,
    private readonly vectorService: VectorService,
  ) {}

  async parseFile(filePath: string, mimetype: string): Promise<string> {
    if (mimetype === 'text/plain') {
      return fs.promises.readFile(filePath, 'utf-8');
    } else if (mimetype === 'application/pdf') {
      const data = await fs.promises.readFile(filePath);
      const pdfData = await pdfParse(data);
      return pdfData.text;
    } else if (
      mimetype === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    ) {
      const result = await mammoth.extractRawText({ path: filePath });
      return result.value;
    } else {
      throw new Error('不支持的文件类型');
    }
  }

  async createArticle(title: string, content: string, filename: string) {
    const article = this.articleRepository.create({ title, content, filename });
    const savedArticle = await this.articleRepository.save(article);
    
    // 异步进行向量化处理
    try {
      const chunkCount = await this.vectorService.processDocument(
        savedArticle.id,
        content,
        {
          title,
          filename,
          uploadTime: savedArticle.uploadTime,
        }
      );
      console.log(`文章 ${savedArticle.id} 向量化完成，生成了 ${chunkCount} 个块`);
    } catch (error) {
      console.error(`文章 ${savedArticle.id} 向量化失败:`, error);
      // 向量化失败不影响文章保存
    }
    
    return savedArticle;
  }

  async findAll() {
    return this.articleRepository.find({ order: { uploadTime: 'DESC' } });
  }

  async findOne(id: number) {
    return this.articleRepository.findOneBy({ id });
  }

  async deleteArticle(id: number) {
    // 删除文章时同时删除相关的向量块
    await this.vectorService.deleteDocumentChunks(id);
    return this.articleRepository.delete(id);
  }

  async getArticleWithChunkCount(id: number) {
    const article = await this.findOne(id);
    if (!article) return null;
    
    const chunkCount = await this.vectorService.getDocumentChunkCount(id);
    return {
      ...article,
      chunkCount,
    };
  }
} 